package com.cardbaobao.cardbabyclient.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.BroadcastController;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.LoansUtils;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Description:
 * Created by FHW
 * on 2017/6/15
 */
public class MobileLoginActivity extends BaseActivity{

    private final int RegisterCode = 1001;

    @BindView(R.id.tw_toolbar)
    TitleBar tw_toolbar;

    @BindView(R.id.edtext_phone)
    EditText mPhoneEd;//
    @BindView(R.id.msg_code)
    EditText mMsgCode;
    @BindView(R.id.send_msg_code)
    TextView mSendMsgCode;

    @BindView(R.id.bt_login)
    Button btLogin;

    private String msgCode = "";
    private String mPhone = "";//手机号码输入框中的手机号码
    private String receivedVerifyPhone;//保存发送验证码成功的手机号码
    private MobileLoginActivity.MyCountDownTimer timer;
    private UserInfo userInfo;

    private String loginRequestFrom="";
    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName(Google.MOBILE_LOGIN);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_verify_code_login_page;
        loginRequestFrom=getIntent().getStringExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S);

        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).keyboardEnable(true).init();
        initIntent();
        String phoneLocal=(mApplication.getUser()==null)?"":mApplication.getUser().getPhone();
        if (!TextUtils.isEmpty(phoneLocal)) {
            if (phoneLocal.length() == 11) {
                mPhoneEd.setText(phoneLocal.substring(0, 3) + "****" + phoneLocal.substring(7));
                mPhoneEd.setSelection(mPhoneEd.getText().length());
                mPhone=phoneLocal;
            }
        }
        mPhoneEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                btLogin.setEnabled(mMsgCode.getText().length()>0&&s.length()>0);
                mPhone=s.toString();
            }
        });
        mMsgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                btLogin.setEnabled(mPhoneEd.getText().length()>0&&s.length()>0);
            }
        });
        tw_toolbar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mobile_login;
    }

    @OnClick({R.id.send_msg_code,R.id.bt_login,R.id.tv_account_login,R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_msg_code:
                checkPhone();
                break;
            case R.id.bt_login:
                String msg_code = mMsgCode.getText().toString().trim();
                if (!msgCode.isEmpty() && msgCode.equals(msg_code)) {
                    if (mPhone.equals(receivedVerifyPhone)) {
                        mApplication.setUser(userInfo);
                        new BroadcastController(mContext).notifyUserLogin();
                        Intent intent = getIntent();
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD,Google.ACTION_MOBILE_LOGIN);
                    } else {
                        ToastUtil.showToast("非法操作");
                    }
                } else if (TextUtils.isEmpty(msgCode)) {
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_input_sms_code_tip));
                } else {
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_sms_code_error_tip));
                }
                break;
            case R.id.tv_account_login:
                mIntent.setClass(mContext, AccountLoginActivity.class);
                mIntent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                        loginRequestFrom);
                mIntent.putExtra("type", 1);
                startActivity(mIntent);
                break;
            case R.id.tv_register:
                Intent registerIntent=new Intent(mContext,RegisterActivity.class);
                registerIntent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,loginRequestFrom);
                startActivityForResult(registerIntent, RegisterCode);
                break;
        }
    }

    /**
     * 发送验证码
     *
     * @param phone 手机号码
     */
    private void sendMsgCode(final String phone) {
        msgCode = String.valueOf(LoansUtils.getMsgCode());
        Observable<String> observable=
                Api.sendSms(phone,Constant.VERIFY_CODE_TYPE,msgCode,Constant.GDX030102);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                dismissProgressDialog();
                msgCode = "";
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object=JSON.parseObject(s);
                if(object.getIntValue("status")==1){
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    timer = new MobileLoginActivity.MyCountDownTimer(90l * 1000l, 1000L);
                    timer.start();
                    mSendMsgCode.setEnabled(false);
                    mSendMsgCode.setText("90s后重发");
                    mSendMsgCode.setTextColor(ContextCompat.getColor(mContext, R.color.color_666666));
                    ToastUtil.showToast("验证码发送成功");
                    receivedVerifyPhone = phone;
                }else{
                    ToastUtil.showToast( object.getString("result"));
                    msgCode = "";
                }
            }
        });
    }

    /**
     * 检测手机号是否注册过
     */
    private void checkPhone() {
        if (RegularUtil.isPhoneNumber(mPhone)) {
            showProgressDialog(false);
            Observable<String> observable=Api.checkPhoneRegistered(mPhone);
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    dismissProgressDialog();
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    JSONObject object=JSON.parseObject(s);
                    if(object.getIntValue("code")==1){
                        userInfo = JSON.parseObject(object.getJSONObject("msg").getString("data"), UserInfo.class);
                        if (userInfo != null) {
                            userInfo.setPhone(mPhone);
                            sendMsgCode(mPhone);
                            GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD,Google.ACTION_MOBILE_LOGIN_CODE);
                        } else {
                            dismissProgressDialog();
                            ToastUtil.showToast("该手机号还未注册,请先注册");
                            startRegisterActivity(mPhone);
                        }
                    }else{
                        dismissProgressDialog();
                        ToastUtil.showToast("该手机号还未注册,请先注册");
                        startRegisterActivity(mPhone);
                    }
                }
            });
        } else {
            ToastUtil.showToast(ApplicationHelper.
                    getApplicationContext().
                    getString(R.string.string_input_phone_tip));
        }
    }

    private void startRegisterActivity(final String phone) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                initIntent();
                mIntent.setClass(MobileLoginActivity.this, RegisterActivity.class);
                mIntent.putExtra("phone", phone);
                startActivityForResult(mIntent, 1001);
            }
        };
        Handler h = new Handler();
        h.postDelayed(runnable, 1000);
    }

    //定时器
    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSendMsgCode.setText(millisUntilFinished / 1000 + "s后重发");
        }

        @Override
        public void onFinish() {
            mSendMsgCode.setText("重新发送");
            mSendMsgCode.setEnabled(true);
            timer = null;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RegisterCode) {
                finish();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("receivedVerifyPhone",receivedVerifyPhone);
        outState.putString("mPhone",mPhone);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        receivedVerifyPhone=savedInstanceState.getString("receivedVerifyPhone");
        mPhone=savedInstanceState.getString("mPhone");
    }
}
